Skip to main content

Modifiers

A modifier transforms a component, producing a modified version of it. Modifiers are applied to a component using a with block.

Applying Modifiers

import { Text, Padding, Background, Rectangle } from ui

export var main: Component = Text("Hello") with {
Padding(8)
Background {
Rectangle(color: Color(0xFF222222))
}
}

Modifiers are applied in order from top to bottom. A modifier applied later wraps the result of all previous modifiers, so order affects the visual result.

Declaring Custom Modifiers

Define a modifier with the modifier keyword. The modified component is available inside the body as the implicit child variable. Like component bodies, modifier bodies can produce multiple sibling components. Declarative if and for are also available — see Declarative Control Flow.

import { Padding } from ui

modifier LargePadding {
child with {
Padding(24)
}
}

Apply it just like any built-in modifier:

import { Padding, Text } from ui

modifier LargePadding {
child with {
Padding(24)
}
}

export var main: Component = Text("Hello") with {
LargePadding()
}

Modifier Properties, State, and Bindings

Like components, modifiers support @property, @binding, and state.

modifier ColoredBackground {
@property color: Color

child with {
Background {
Rectangle(color: self.color)
}
}
}

Modifiers on Multi-Child Components

When a modifier is applied to a component that yields multiple children, the modifier is applied separately to each child — but it is the same modifier instance for all of them. This means any state inside the modifier is shared across every child it wraps.

import { VStack, Text, TapGesture, Background, Rectangle } from ui

component Two {
Text("First")
Text("Second")
}

modifier Highlight {
active: Bool = false

child with {
TapGesture(fun (_) {
self.active = not self.active
})
Background {
Rectangle(color: self.active ? Color(0xFFFF0000) : Color(0xFFDFDFDF))
}
}
}

component Main {
VStack {
Two() with {
Highlight()
}
}
}

export var main: Component = Main()

In this example both Text components are siblings in the VStack and are spaced by it independently. Each gets its own background applied by Highlight. However, because both children share the same Highlight instance, clicking either one toggles self.active for the whole modifier — turning both backgrounds red simultaneously.

Exporting Modifiers

Modifiers can be exported from a module:

export modifier LargePadding {
child with {
Padding(24)
}
}

See Modules for details.